package org.jpro.config;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Scope;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * <P>功能描述 : http连接池配置 </P>
 * <P>File name : HttpConfig </P>
 * <P>Author : 王泽浩 </P>
 * <P>E-Mail : 1028625100@qq.com </P>
 * <P>Date : 2017/3/15 上午11:11</P>
 */
@Getter
@Setter
@ToString
@Configuration
@ConfigurationProperties(prefix = "spring.http")
public class HttpConfig {

    /**
     * 最大连接数
     */
    private int maxTotal = 100;

    /**
     * 最大并发数
     */
    private int defaultMaxPerRoute = 30;

    /**
     * 定义连接管理器
     * @return
     */
    @Bean("connectionManager")
    public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
        poolingHttpClientConnectionManager.setMaxTotal(this.maxTotal);// 最大连接数
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(this.defaultMaxPerRoute);// 最大并发数
        return poolingHttpClientConnectionManager;
    }

    /**
     * 定义HttpClient构建器
     * @param connectionManager 连接管理器
     * @return
     */
    @Bean("httpClientBuilder")
    @DependsOn("connectionManager")
    public HttpClientBuilder httpClientBuilder(PoolingHttpClientConnectionManager connectionManager) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(connectionManager);
        return httpClientBuilder;
    }

    /**
     * 定义httpClient对象，该bean一定是多例的
     */
    @Bean("httpClient")
    @Scope("prototype")
    @DependsOn("httpClientBuilder")
    public CloseableHttpClient closeableHttpClient(HttpClientBuilder httpClientBuilder) {
        return httpClientBuilder.build();
    }

}
